package com.ycq.cloud.zuul.ZuulFilterConfig;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class PreZuulFilter  extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(PreZuulFilter.class);
    /**     * filterType：返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
     *  * pre：路由之前
     *  * routing：路由之时
     *  * post： 路由之后
     *  * error：发送错误调用
     *  *     * @return     */

    @Override
    public String filterType() {
        return "pre";           //pre:之前 ，这里表示会在请求被路由之前执行
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request= RequestContext.getCurrentContext().getRequest();
        String host=request.getRemoteHost();
        PreZuulFilter.LOGGER.info("请求的host:{}", host);
        return null;
    }


    /**
     * * 过滤器的具体逻辑
     *  * @return
     *  * @throws ZuulException
     *  */
//    @Override
//    public Object run() throws ZuulException {
//        RequestContext ctx = RequestContext.getCurrentContext();
//        HttpServletRequest request = ctx.getRequest();
//        Object accessToken = request.getParameter("uid");
//        if(accessToken == null) {
//            ctx.setSendZuulResponse(false);
//            ctx.setResponseStatusCode(401);
//            ctx.getResponse().setCharacterEncoding("GBK");
//            try {
//                ctx.getResponse().getWriter().write("缺少uid字段!");
//            }catch (Exception e){}
//        }
//        return null;
//    }

}
